package com.origin.app.page.map

import android.Manifest
import android.content.Intent
import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import androidx.recyclerview.widget.LinearLayoutManager
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.amap.api.maps.AMap
import com.amap.api.maps.CameraUpdateFactory
import com.amap.api.maps.model.CameraPosition
import com.amap.api.maps.model.LatLng
import com.amap.api.maps.model.Marker
import com.jeremyliao.liveeventbus.LiveEventBus
import com.origin.app.MyApplication
import com.origin.app.R
import com.origin.app.bean.CompanyPointBean
import com.origin.app.databinding.ActivityAppMapBinding
import com.origin.app.dialog.CompanyListDialog
import com.origin.app.page.base.BaseActivity
import com.origin.app.page.location_records.LocationRecordsActivity
import com.origin.app.page.map.adapter.NavAdapter
import com.origin.app.service.SignalrService
import com.origin.app.utils.MapUtils
import com.origin.app.utils.NetAppUtils
import com.origin.uilibrary.xrecycleview.adapter.BaseRecycleAdapter
import com.origin.utils.log.LogUtils
import com.origin.utils.permissions.OnPermissionPageCallback
import com.origin.utils.permissions.PermissionsUtils
import com.origin.utils.statusBar.StatusBarUtil
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach


class AppMapActivity :
    BaseActivity<ActivityAppMapBinding, AppMapViewModel>(R.layout.activity_app_map),
    View.OnClickListener ,BaseRecycleAdapter.OnItemClickListener<CompanyPointBean>{

    private val navAdapter: NavAdapter by lazy {
        NavAdapter(viewModel.navList, this@AppMapActivity)
    }
    private   val slideInBottomAnimation: Animation   by lazy {
        AnimationUtils.loadAnimation(this@AppMapActivity, R.anim.slide_in_bottom)
    }
    private   val slideOutBottomAnimation: Animation   by lazy {
        AnimationUtils.loadAnimation(this@AppMapActivity, R.anim.slide_out_bottom)
    }
    companion object {
        fun launcher() {
            MyApplication.getInstance().getCurrentActivity()?.apply {
                val self = this
                AMapLocationClient.updatePrivacyShow(this, true, true)
                AMapLocationClient.updatePrivacyAgree(this, true)
                PermissionsUtils.simpleRequestPermissions(this,
                    Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS,
                    onPermissionPageCallback = object : OnPermissionPageCallback {
                        override fun onGranted(permissions: MutableList<String>?) {

                            val mLocationOption = AMapLocationClientOption();
                            mLocationOption.locationMode =
                                AMapLocationClientOption.AMapLocationMode.Hight_Accuracy
                            mLocationOption.interval = 2000;


                            val intent = Intent(self, AppMapActivity::class.java)
                            startActivity(intent)
                        }

                        override fun onDenied(permissions: MutableList<String>?) {

                        }

                    })


            }
        }
    }

    override fun initContentView() {

        contentViewBinding.appMapViewModel = viewModel
    }

    private val selectCompanyPointBean=CompanyPointBean()
    override fun initSavedInstanceState(savedInstanceState: Bundle?) {
        super.initSavedInstanceState(savedInstanceState)
        StatusBarUtil.statusBarLightMode(this)
        contentViewBinding.mapView.onCreate(savedInstanceState)
        contentViewBinding.btn.setOnClickListener(this)
        contentViewBinding.btnNormal.setOnClickListener(this)
        contentViewBinding.btnException.setOnClickListener(this)
        contentViewBinding.btnOffline.setOnClickListener(this)
        contentViewBinding.btnNotOnline.setOnClickListener(this)
        contentViewBinding.imgUser.setOnClickListener(this)
        // bottom_marker_point_info
        contentViewBinding.bottomMarkerPointInfo.tvTrack.setOnClickListener(this)
        contentViewBinding.bottomMarkerPointInfo.tvFence.setOnClickListener(this)
        contentViewBinding.navList.layoutManager = LinearLayoutManager(this)
        contentViewBinding.navList.adapter = navAdapter
        navAdapter.mItemClickListener=this
        contentViewBinding.selectCompanyPointBean = selectCompanyPointBean
        contentViewBinding.companyPointBean= CompanyPointBean().apply {
            this.name="名称";
            this.company_Name="机构"
        }
        SignalrService.launcher(this@AppMapActivity)
        LiveEventBus.get("location",CompanyPointBean::class.java).observe(this){
            if(contentViewBinding.homeId.isOpen){
                viewModel.imRefreshNavList(it)
            }
            // 刷新全部数据
            viewModel.imRefreshMarkerList(it)
        }
    }

    override fun setMutableLiveDataListener() {

        viewModel.refreshNavListMutableLiveData
            .debounce(500L)
            .onEach {
                LogUtils.__e("navAdapter 刷新x")
                navAdapter.notifyItemRangeChanged(0, viewModel.navList.size)
            }.launchIn(this)


        viewModel.refreshListMutableSharedFlow
            .debounce(500L)
            .onEach {
//                LogUtils.__e("数值 刷新x")
                viewModel.refreshNum()
            }.launchIn(this)

        viewModel.refreshListMutableLiveData.observe(this) {
            showLocationMarker()
            viewModel.refreshNum()
            // 发送server
            SignalrService.addGroups(this@AppMapActivity, viewModel.companyCodeList)
        }
        viewModel.refreshNetPointInfoMutableLiveData.observe(this){
            selectCompanyPointBean.refreshPic(NetAppUtils.staticFileHost+it.photo)
            selectCompanyPointBean.phone=it.phone
        }
    }


    private fun showLocationMarker() {

        val markers = mutableListOf<Marker>()
        contentViewBinding.mapView.map.clear()
        MapUtils.clearMarkerMap()
        viewModel.companyPointList.forEach {
            val marker: Marker =
                contentViewBinding.mapView.map.addMarker(
                    MapUtils.getMarker(it.equipmentState, it.isCard)
                        .position(LatLng(it.gcJ02.lat, it.gcJ02.lng))
                        .title(it.name)
//                    .snippet("DefaultMarker")
                )
            marker.`object`=it
            MapUtils.classificationMarker(it.equipmentState, marker)
            markers.add(marker)
        }


        MapUtils.fitMarkersToBounds(markers, contentViewBinding.mapView.map);
        contentViewBinding.mapView.map.setOnMarkerClickListener(object :
            AMap.OnMarkerClickListener {
            override fun onMarkerClick(master: Marker?): Boolean {
              return  showBottomInfo(master)
            }

        })
        contentViewBinding.mapView.map.setOnMapClickListener {
            LogUtils.__e("点击了 地图")
            if(actionMaskClick){
                actionMaskClick=false
                return@setOnMapClickListener
            }
            contentViewBinding.bottomMarkerPointInfo.dialogBottomMarkerPointInfoRoot.startAnimation(
                slideOutBottomAnimation
            )
            contentViewBinding.bottomMarkerPointInfo.dialogBottomMarkerPointInfoRoot.visibility =
                View.GONE
        }

    }

    private fun showBottomInfo(master: Marker?):Boolean{
        LogUtils.__e("点击了 Marker")
        actionMaskClick=true
        viewModel.viewModelSuspend{
            delay(500)
            actionMaskClick=false;
        }
        if(master==null){
            return false;
        }
        var bean= master.`object`;

        if (bean !is CompanyPointBean){
            return false;
        }
        // bottom_marker_point_info
        selectCompanyPointBean.refresh(bean)
        viewModel.getNetPointInfo(bean)
        if( contentViewBinding.bottomMarkerPointInfo.dialogBottomMarkerPointInfoRoot.visibility!=View.VISIBLE){
            contentViewBinding.bottomMarkerPointInfo.dialogBottomMarkerPointInfoRoot.visibility=View.VISIBLE
            // 加载动画
            contentViewBinding.bottomMarkerPointInfo.dialogBottomMarkerPointInfoRoot.startAnimation(slideInBottomAnimation)
        }
        // 应用动画
        return false;
    }


    private var actionMaskClick=false
    val markerPointInfoDialogCallback: (Int, CompanyPointBean) -> Unit = { type, point ->
    }

    override fun onDestroy() {
        super.onDestroy()
        contentViewBinding.mapView.onDestroy()
    }


    var isFirst = true;
    override fun onResume() {
        super.onResume()
        contentViewBinding.mapView.onResume()
        if (isFirst) {
            isFirst = false;
            viewModel.getCompanyListUrl()
        }

    }

    override fun onPause() {
        super.onPause()
        contentViewBinding.mapView.onPause()
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        contentViewBinding.mapView.onSaveInstanceState(outState)
    }

    private fun checkBtnState(tag: Int) {
        if (viewModel.selectIndex.get() != tag) {
            MapUtils.showMarker(tag)
            viewModel.selectIndex.set(tag)
            return
        } else {
            MapUtils.showAllMarker(tag)
            viewModel.selectIndex.set(0)
        }
    }

    override fun onClick(view: View?) {
        if (view == null) {
            return;
        }

        if (view == contentViewBinding.btn) {
            CompanyListDialog(viewModel.companyBeanList, this) {
                viewModel.checkCompanyPoint()
            }.show(supportFragmentManager, "CompanyListDialog")
            return
        }
        if (view == contentViewBinding.btnNormal) {
            checkBtnState(1);
            return
        }
        if (view == contentViewBinding.btnException) {
            checkBtnState(2);
            return
        }
        if (view == contentViewBinding.btnOffline) {
            checkBtnState(3);
            return
        }
        if (view == contentViewBinding.btnNotOnline) {
//            checkBtnState(4);
            viewModel.resetNavNotOnlineList()
            navAdapter.notifyDataSetChanged()
            contentViewBinding.homeId.openDrawer(Gravity.START)
            return
        }
        if (view == contentViewBinding.imgUser) {
            viewModel.resetNavList()
            navAdapter.notifyDataSetChanged()
            contentViewBinding.homeId.openDrawer(Gravity.START)
            return
        }
        if(view==contentViewBinding.bottomMarkerPointInfo.tvTrack){
            LogUtils.__e("选择内容    ${selectCompanyPointBean.phone}")
            LocationRecordsActivity.launcher(selectCompanyPointBean)
            return
        }
        if (view==contentViewBinding.bottomMarkerPointInfo.tvFence){
            viewModel.getTaskIdByPolygon(selectCompanyPointBean,contentViewBinding.mapView.map)
            return
        }
    }

    override fun onItemClick(position: Int, item: CompanyPointBean, view: View?) {
        val mapMarkerBean = MapUtils.getCompanyPointBeanByCode(item.in_Code)
        contentViewBinding.homeId.closeDrawer(Gravity.START)
        val mAMap= contentViewBinding.mapView.map
        val cameraPosition = CameraPosition(LatLng(item.gcJ02.lat, item.gcJ02.lng), 25f, 0f, 0f)
        val cameraUpdate = CameraUpdateFactory.newCameraPosition(cameraPosition)
        mapMarkerBean?.showInfoWindow()
        mAMap.moveCamera(cameraUpdate)
        showBottomInfo(mapMarkerBean)
    }

}